/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.octopeer.utilities;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

import java.io.File;
import java.io.StringWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 *
 * @author andria
 */
public class XMLTools {
    private DocumentBuilderFactory dbf;
    public DocumentBuilder db;
    
    public XMLTools() throws ParserConfigurationException {
        dbf = DocumentBuilderFactory.newInstance();
        db = dbf.newDocumentBuilder();	
    }
    
    public void writeXMLFile(Document doc, String filename) throws Exception {
        // Prepare the DOM document for writing
        Source source = new DOMSource(doc);

        // Prepare the output file
        File file = new File(filename);
        Result result = new StreamResult(file);

        // Write the DOM document to the file
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(source, result);
    }
    
    public String writeXMLString(Document doc) {
        StringWriter stringwriter;
        stringwriter = new StringWriter();
        OutputFormat format = new OutputFormat(doc);
        format.setIndenting(false);
        format.setEncoding("UTF-8");
        format.setOmitXMLDeclaration(true);
        
        //to generate output to console use this serializer
        XMLSerializer serializer = new XMLSerializer(stringwriter, format);	
        try {

            serializer.serialize(doc);
        } catch (IOException ex) {
            Logger.getLogger(XMLTools.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return stringwriter.toString().replaceAll("&#xd;","\r");
    }    
}
